import { Component, ViewEncapsulation, OnInit } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import {EmailValidator, EqualPasswordsValidator} from '../../theme/validators';

import { UserService } from '../user/user.service';
import { User } from '../user/user';

import { Router } from '@angular/router';

@Component({
  selector: 'password',
  encapsulation: ViewEncapsulation.None,
  styles: [require('./password.scss')],
  template: require('./password.html'),
})
export class Password implements OnInit {

  public form: FormGroup;
  public oldPassword: AbstractControl;

  public passwords:FormGroup;
  public password: AbstractControl;
  public repeatPassword: AbstractControl;
  public submitted: boolean = false;
  public user: User;
  private errorMessage: string;
  private currentUser:string;

  constructor(
    fb: FormBuilder,
    private userService: UserService,
    private router: Router
  ) {

    this.form = fb.group({
      'oldPassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
      'passwords': fb.group({
        'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
        'repeatPassword': ['', Validators.compose([Validators.required, Validators.minLength(4)])]
      }, {validator: EqualPasswordsValidator.validate('password', 'repeatPassword')})
    });

    this.oldPassword = this.form.controls['oldPassword'];
    this.passwords = <FormGroup> this.form.controls['passwords'];
    this.password = this.passwords.controls['password'];
    this.repeatPassword = this.passwords.controls['repeatPassword'];
  }

  ngOnInit () {
    this.currentUser = localStorage.getItem('accessToken');
  }

  public onSubmit(values: Object): void {

    this.submitted = true;
    if (this.form.valid) {
      this.userService.changepassword(this.currentUser, this.oldPassword.value, this.password.value)
        .then(user => this.changepassword(user), error => this.errorMessage = '修改密码失败，请检查。');
    }
  }

  private changepassword(user :User) {
    this.user = user;
      //判断结果
      if (this.user && this.user.user_id > 0) {
        this.errorMessage = null;
        console.log(this.user.login_username);
        this.router.navigateByUrl('pages');
      } else {
        this.errorMessage = '修改密码失败，请检查。';
      }
    }
}
